//入口函数
$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useUpdateRows, useDataIndexChange }) {
    var mstform = $NG.getCmpApi("p_form_Milestone_Plan_m"); //里程碑计划主表
    var dgrid1 = $NG.getCmpApi("p_form_Milestone_Plan_d"); //里程碑计划明细
    var dgrid2 = $NG.getCmpApi("p_form_Milestone_Task_d"); //里程碑任务明细
    var dgrid3 = $NG.getCmpApi("p_form_Milestone_Repay_d"); //里程碑回款明细
    var dtoolbar1 = $NG.getCmpApi("toolbar_p_form_Milestone_Plan_d");
    var dtoolbar2 = $NG.getCmpApi("toolbar_p_form_Milestone_Task_d");
    var dtoolbar3 = $NG.getCmpApi("toolbar_p_form_Milestone_Repay_d");
  
    ////////////////////////////////////////////////////////////--toolbar--////////////////////////////////////////////////////////////
    dtoolbar1.hideButton("addrow");
    dtoolbar1.hideButton("attachment");
    dtoolbar2.hideButton("addrow");
    dtoolbar2.hideButton("attachment");
    dtoolbar3.hideButton("addrow");
    dtoolbar3.hideButton("deleterow");
    dtoolbar3.hideButton("attachment");
    dtoolbar1.insert({
      id: "planadd",
      text: "新增里程碑",
      iconCls: "icon-New",
    });
    dtoolbar2.insert({
      id: "taskadd",
      text: "新增里程碑任务",
      iconCls: "icon-New",
    });
    dtoolbar2.insert({
      id: "repayadd",
      text: "新增回款任务",
      iconCls: "icon-New",
    });
  
    ////////////////////////////////////////////////////////////--初始化--////////////////////////////////////////////////////////////
    if ($NG.getCmpApi("p_form_Milestone_Plan_m").getItem("phid_pc").getValue()) {
      getPtInfoByPhid();
    }
  
    ////////////////////////////////////////////////////////////--useClick--////////////////////////////////////////////////////////////
    useClick(async function ({ args }) {
      planadd();
    }, "planadd");
    useClick(async function ({ args }) {
      taskaddClick();
    }, "taskadd");
    useClick(async function ({ args }) {
      repayadd();
    }, "repayadd");
    useClick(async function ({ args }) {
      setTimeout(function () {
        updateRepay();
      }, 500);
    }, "deleterow");
  
    //按钮单击事件
    // dtoolbar3.getItem("deteterow").getRef().click();
  
    ////////////////////////////////////////////////////////////--useValuesChange--////////////////////////////////////////////////////////////
    useValuesChange(({ args }) => {
      getPtInfoByPhid();
    }, "p_form_Milestone_Plan_m.phid_pc");
    if (page.oType == "add" || page.oType == "copy") {
      useValuesChange(({ args }) => {
        if (dgrid3) {
          $NG.execServer("getPaymentPlanByPhid_pc", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
            if (res.count == 0) return;
            const data = JSON.parse(res.data);
            console.log("getPaymentPlanByPhid_pc");
            console.log(res.data);
            var gridArr = [];
            var gridCount = res.count;
            for (var i = 0; i < gridCount; i++) {
              var gridObj = {};
              //对表体字段进行赋值,可以取数据库中的值进行赋值
              gridObj.u_fund_name = data[i].extendObjects.u_hklcb;
              gridObj.amt = data[i].extendObjects.u_hk_amt;
              gridObj.u_hkzq = data[i].extendObjects.u_hkzq;
              // gridObj.u_plan_dt = data[i].extendObjects.u_total_daily_amt;
              gridArr.push(gridObj);
            }
            //调用新增表体行数据的函数
            dgrid3.addRows(gridArr);
          });
        }
      }, "p_form_Milestone_Plan_m.phid_pc");
    }
    ////////////////////////////////////////////////////////////--useUpdateRows--////////////////////////////////////////////////////////////
    // useUpdateRows(({ args, table }) => {
    //   console.log("useUpdateRows:");
    //   updateRepay();
    // }, "p_form_Milestone_Task_d");
    ////////////////////////////////////////////////////////////--useDataIndexChange--////////////////////////////////////////////////////////////
    useDataIndexChange(({ args, instance }) => {
      console.log("useDataIndexChange:");
      updateRepay();
    }, "p_form_Milestone_Plan_d.u_plan_start_dt");
    useDataIndexChange(({ args, instance }) => {
      console.log("useDataIndexChange:");
      updateRepay();
    }, "p_form_Milestone_Plan_d.u_plan_end_dt");
    useDataIndexChange(({ args, instance }) => {
      console.log("useDataIndexChange:");
      updateRepay();
    }, "p_form_Milestone_Task_d.u_intervaltime");
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--function--////////////////////////////////////////////////////////////
    function getPtInfoByPhid() {
      if (mstform.getItem("phid_pc").getValue()) {
        $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
          const datas = JSON.parse(res.data)[0].extendObjects;
          console.log("getPtInfoByPhid:");
          console.log(datas);
          $NG.updateState((updater) => {
            updater.data.p_form_Milestone_Plan_m.setProps({
              //项目类型
              u_wbs_type: { value: datas.type_phid, label: datas.type_name },
            });
          });
        });
      }
    }
    function filter_help(table,key,d='rel_key1'){
        //遍历表格
      let str = ""
      const _arr = table.getRows()
      console.log(_arr);
      const _is = []
      _arr.forEach(item=>{
        _is.push(String(item[d]))
      })
      if(_is.length==0){
      }else{
        str = `and ${key} not in (`
        _is.forEach((item,index)=>{
          if(index>0){
            str+=`,'${item}'`
          } else {
            str+=`'${item}'`
          }
        })
        str+=')'
      }
      console.log(str);
      return str
    }
    function planadd() {
      if (!mstform.getItem("u_wbs_type").getValue()) {
        $NG.alert("请先选择项目类型");
        return;
      }
      
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "view_Task_Templates_d",
          valueField: "phid",
          labelField: "u_milestone_name",
          clientSqlFilter: `u_wbs_type= ${mstform.getItem("u_wbs_type").getValue()} ${filter_help(dgrid1,'phid')}`,
        })
        .then((data) => {
          try {
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = data[i].origin.phid;
                gridObj.u_phase = data[i].origin.u_phase || "";
                gridObj.u_milestone_no = data[i].origin.u_milestone_no || "";
                gridObj.u_milestone_name = data[i].origin.u_milestone_name || "";
                gridObj.u_milestone_type = data[i].origin.u_milestone_type_id;
                gridObj.u_milestone_type_EXName = data[i].origin.u_milestone_type_name || "";
                gridObj.u_start_dt = data[i].origin.u_start_dt || "";
                gridObj.u_end_dt = data[i].origin.u_end_dt || "";
                gridArr.push(gridObj);
              }
              console.log("planadd gridArr:");
              console.log(gridArr);
              dgrid1.addRows(gridArr);
              dgrid1.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function taskaddClick() {
      if (!dgrid1.getSelectedData()[0]) {
        $NG.alert("请先选择对应的里程碑");
        return;
      }
      // console.log("u_wbs_type" + mstform.getItem("u_wbs_type").getValue());
      // console.log("u_milestone_no" + dgrid1.getSelectedData()[0].u_milestone_no);
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "Task_Templates_dd",
          valueField: "dd.phid",
          labelField: "dd.deliverables",
          clientSqlFilter:
            "d.u_wbs_type = " + mstform.getItem("u_wbs_type").getValue() + " and d.u_milestone_no='" + dgrid1.getSelectedData()[0].u_milestone_no + "'" +filter_help(dgrid2, 'dd.u_deliverables',"u_deliverables"),
        })
        .then((data) => {
          try {
            // console.log(data);
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              // console.log(data.length);
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
                gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
                gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
                gridObj.u_deliverables = data[i].origin.u_deliverables;
                gridObj.u_deliverable_type = data[i].origin.u_deliverable_type;
                gridObj.u_busid = data[i].origin.u_busid;
                gridObj.u_busid_EXName = data[i].origin.busname || "";
                gridObj.u_standardtype = data[i].origin.u_standardtype;
                gridObj.u_intervaltime = data[i].origin.u_intervaltime;
                gridObj.u_isneed = data[i].origin.u_isneed;
                gridObj.u_donepoint = data[i].origin.u_donepoint;
                gridObj.u_sendmsg = data[i].origin.u_sendmsg;
                gridArr.push(gridObj);
              }
              console.log("taskadd gridArr:");
              console.log(gridArr);
              dgrid2.addRows(gridArr);
              dgrid2.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function repayadd() {
      if (!dgrid1.getSelectedData()[0]) {
        $NG.alert("请先选择对应的里程碑");
        return;
      }
      
      $NG.external
        .openNGHelp({
          type: "NGMultipleHelp",
          helpId: "p_form_payment_plan_d",
          valueField: "d.phid",
          labelField: "d.u_hklcb",
          clientSqlFilter: "m.phid_pc = " + mstform.getItem("phid_pc").getValue() +filter_help(dgrid2,'d.u_hklcb',"u_fund_name"),
        })
        .then((data) => {
          try {
            // console.log(data);
            if (Array.isArray(data) && data.length > 0) {
              var gridArr = [];
              // console.log(data.length);
              for (var i = 0; i < data.length; i++) {
                var gridObj = {};
                gridObj.rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
                gridObj.u_plan_start_dt = dgrid1.getSelectedData()[0].u_plan_start_dt;
                gridObj.u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
                gridObj.u_deliverables = "回款任务";
                gridObj.u_deliverable_type = "1";
                gridObj.u_busid = 77;
                gridObj.u_busid_EXName = "承包合同收款";
                gridObj.u_standardtype = "4";
                gridObj.u_intervaltime = "";
                gridObj.u_isneed = "2";
                gridObj.u_donepoint = "2";
                gridObj.u_sendmsg = "1";
                gridObj.u_fund_name = data[i].origin.u_hklcb;
                gridObj.amt = data[i].origin.u_hk_amt;
                gridArr.push(gridObj);
              }
              console.log("repayadd gridArr:");
              console.log(gridArr);
              dgrid2.addRows(gridArr);
              dgrid2.refreshView();
            } else {
              console.error("返回的数据无效或为空:", data);
            }
          } catch (error) {
            console.error("处理数据时出错:", error);
          }
        })
        .then(() => {
          try {
            setTimeout(function () {
              updateRepay();
            }, 500);
          } catch (error) {
            console.error("调用 updateRepay 时发生错误:", error);
          }
        })
        .catch((error) => {
          console.error("打开NGHelp时发生错误:", error);
        });
    }
    function updateRepay(params) {
      // 获取 dgrid1 的 u_plan_end_dt 和 rel_key1
      // if (dgrid1.getSelectedData()[0]) {
      //   var rel_key1 = dgrid1.getSelectedData()[0].rel_key1;
      //   var u_phase = dgrid1.getSelectedData()[0].u_phase;
      //   var u_milestone_no = dgrid1.getSelectedData()[0].u_milestone_no;
      //   var u_milestone_name = dgrid1.getSelectedData()[0].u_milestone_name;
      //   var u_plan_end_dt = dgrid1.getSelectedData()[0].u_plan_end_dt;
      // } else {
      //   var rel_key1 = "";
      //   var u_phase = "";
      //   var u_milestone_no = "";
      //   var u_milestone_name = "";
      //   var u_plan_end_dt = "";
      // }
      var selectedData = dgrid1.getSelectedData()[0] || {};
      var rel_key1 = selectedData.rel_key1 || "";
      var u_phase = selectedData.u_phase || "";
      var u_milestone_no = selectedData.u_milestone_no || "";
      var u_milestone_name = selectedData.u_milestone_name || "";
      var u_plan_start_dt = selectedData.u_plan_start_dt || "";
      var u_plan_end_dt = selectedData.u_plan_end_dt || "";
  
      // 用于存储 dgrid2 中符合条件的 u_fund_name
      var fundNames = [];
      var rel_key1arr = [];
      // 遍历 dgrid2，找到 rel_key1 相等的行并记录 u_fund_name
      dgrid2.getRows().forEach(function (item) {
        // item.u_plan_end_dt = u_plan_end_dt;
        let newDate = null;
        if (u_plan_start_dt) {
          newDate = new Date(u_plan_start_dt);
          if (!isNaN(newDate)) {
            newDate.setDate(newDate.getDate() + item.u_intervaltime); // 加上 u_hkzq 天数
            item.u_plan_start_dt = newDate; // 更新 u_plan_dt
          } else {
            console.error("Invalid date format:", u_plan_start_dt);
            item.u_plan_start_dt = null;
          }
        } else {
          item.u_plan_start_dt = null;
        }
        rel_key1arr.push(item.rel_key1);
        if (item.rel_key1 === rel_key1) {
          fundNames.push(item.u_fund_name);
        }
      });
      console.log("rel_key1arr:");
      console.log(rel_key1arr);
      console.log("fundNames:");
      console.log(fundNames);
      // 遍历 dgrid3，更新符合条件的行的 u_plan_dt
      dgrid3.getRows().forEach(function (item) {
        if (fundNames.includes(item.u_fund_name)) {
          item.u_phase = u_phase;
          item.u_milestone_no = u_milestone_no;
          item.u_milestone_name = u_milestone_name;
          item.u_plan_end_dt = u_plan_end_dt;
          // 计算新的 u_plan_dt
          let newDate = null;
          if (u_plan_end_dt) {
            newDate = new Date(u_plan_end_dt);
            if (!isNaN(newDate)) {
              newDate.setDate(newDate.getDate() + item.u_hkzq); // 加上 u_hkzq 天数
              item.u_plan_dt = newDate; // 更新 u_plan_dt
            } else {
              console.error("Invalid date format for u_plan_end_dt:", u_plan_end_dt);
              item.u_plan_dt = null;
            }
          } else {
            item.u_plan_dt = null;
          }
        } else {
          item.u_phase = "";
          item.u_milestone_no = "";
          item.u_milestone_name = "";
          item.u_plan_end_dt = "";
        }
      });
      dgrid2.refreshView();
      dgrid3.refreshView();
    }
    // 表体插入重复数据的检测方法
    function insertIfNotExists(data) {
      // 获取当前表体的所有行
      const existingRows = $NG.getCmpApi("p_form_Milestone_Task_d").getRows();
      // 创建一个Map来快速查找u_htzjxx
      const existingRowsMap = new Map(existingRows.map((row) => [row.u_htzjxx, true]));
  
      // 收集需要插入的新行（这里假设我们直接插入整个data对象，但您可能只需要部分）
      const newRows = [];
  
      data.forEach((item) => {
        // 检查该item的origin.phid是否已在existingRows中
        if (!existingRowsMap.has(item.origin.phid)) {
          // 如果不存在，则添加到newRows中（这里以整个item为例）
          newRows.push(item);
  
          // 注意：如果您只想插入部分数据，请在这里进行修改
          // 例如：newRows.push({ /* 仅包含您想插入的字段 */ });
        }
        // 如果存在，则不执行任何操作，因为不需要插入
      });
  
      // 现在，newRows包含了所有需要插入的行
      // 接下来，您可能需要调用另一个API或函数来实际执行插入操作
      // 假设有一个函数叫做 insertRows，它接受一个数组并插入到表体中
      // insertRows(newRows); // 这需要您自己实现或调用现有的API
  
      // 注意：这里我没有实现insertRows函数，因为它将依赖于您的具体API或框架
      console.log("需要插入的数组对象:", newRows); // 仅用于演示
      return newRows;
    }
  });
  